/**
 * Description: PWM驱动蜂鸣器
 * File: buz.c |Time: 2021-05-12 17:07
 */

#include "gpio.h"
#include "pwm.h"

void hal_pwm_init(void)
{
    // 1. GPIO设置蜂鸣器引脚功能为pwm
    hal_gpio_init(GPIOC, GPIO_PIN_14, ALT2);

    // 2. 设置一级分频值
    PWM.TCFG0 &= ~(0xFF << 8);
    PWM.TCFG0 |= (100 << 8);

    // 3. 设置二级分频值
    PWM.TCFG1 &= ~(0xF << 8);
    PWM.TCFG1 |= (0x1 << 8);

    // 4. 设置定时器计数器初始值
    // 5. 设置定时器比较计数器比较值
    hal_pwm_waves(T2, 500, 100);


    // 6. 打开定时器手动更新位
    hal_pwm_option(T2, T_MANUAL, ON);
    // 7. 打开定时器自动更新位
    hal_pwm_option(T2, T_AUTO, ON);
    // 8. 关闭定时器手动更新位
    hal_pwm_option(T2, T_MANUAL, OFF);
    // 9. 打开定时器反转位
    hal_pwm_option(T2, T_INVERTER, ON);
    // 10.打开定时器使能位
    hal_pwm_option(T2, T_ENABLE, ON);

}

// PWM 配置
void hal_pwm_option(timer_t T, optype_t op, switch_t s)
{
    int pos;

    if (op == T_DEAD_ZONE) 
    {
        pos = 4;
    } else {
        if (T == T0) 
        {
            pos = op;
        } else {
            pos = T*4 + 4 + op;
        }
    }

    if (s == ON) 
    {
        PWM.TCON |= (0x1 << pos);
    } else {
        PWM.TCON &= ~(0x1 << pos);
    }
}

// PWM 波形控制
void hal_pwm_waves(timer_t T, int tcntb, int tcmpb)
{
    switch (T) 
    {
        case T0:
            PWM.TCNTB0 = tcntb;
            PWM.TCMPB0 = tcmpb;
            break;
        case T1:
            PWM.TCNTB1 = tcntb;
            PWM.TCMPB1 = tcmpb;
            break;
        case T2:
            PWM.TCNTB2 = tcntb;
            PWM.TCMPB2 = tcmpb;
            break;
        case T3:
            PWM.TCNTB3 = tcntb;
            PWM.TCMPB3 = tcmpb;
            break;
        case T4:
            PWM.TCNTB4 = tcntb;
            break;
        default:
            break;
    }
}



